package com.pimee.service.admin.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.pimee.common.util.DateUtil;
import com.pimee.common.util.Md5Util;
import com.pimee.common.util.RandomUtil;
import com.pimee.common.util.bean.BeanUtils;
import com.pimee.mapper.SysDeptMapper;
import com.pimee.mapper.SysUserPostMapper;
import com.pimee.mapper.SysUserRoleMapper;
import com.pimee.mapper.ext.ExtSysUserMapper;
import com.pimee.model.SysDept;
import com.pimee.model.SysPost;
import com.pimee.model.SysRole;
import com.pimee.model.SysUser;
import com.pimee.model.SysUserPost;
import com.pimee.model.SysUserRole;
import com.pimee.model.vo.SysUserVo;
import com.pimee.service.BaseService;
import com.pimee.service.admin.ISysUserService;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

@Slf4j
@Service
public class SysUserService extends BaseService<SysUser> implements ISysUserService {

	@Autowired
	private ExtSysUserMapper extSysUserMapper;
	@Autowired
	private SysDeptMapper sysDeptMapper;
	@Autowired
	private SysUserPostMapper sysUserPostMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Override
	public PageInfo<SysUserVo> pageUser(Map<String, Object> params) {
		log.info("===> 用户列表分页查询...");
		startPage(params);// 设置分页
		List<SysUserVo> list = extSysUserMapper.listUser(params);
		return new PageInfo<>(list);
	}

	@Override
	public SysUser selectOneByAccount(String account) {
		SysUser sysUser = new SysUser();
		sysUser.setLoginName(account);
		return mapper.selectOne(sysUser);
	}

	@Override
	public void addUser(SysUser sysUser) {
		Date now = DateUtil.now();
		sysUser.setCreateTime(now);
		sysUser.setUpdateTime(now);
		sysUser.setDelFlag("0");
		sysUser.setUserType("01"); // 避免生成00
		// 一个Byte占两个字节，此处生成的3字节，字符串长度为6
		String salt = RandomUtil.getRandomChar(6);
		sysUser.setSalt(salt);
		String password = Md5Util.getMd5Passwd(sysUser.getPassword(), sysUser.getSalt());
		sysUser.setPassword(password);
		this.saveNotNull(sysUser);
		// 新增用户与岗位管理
		insertUserPost(sysUser);
	}

	@Override
	public void updateUser(SysUser sysUser) {
		if (sysUser.getPostIds() != null && sysUser.getPostIds().length > 0) {
			Long userId = sysUser.getUserId();
			// 删除用户与岗位关联
			Example example = new Example(SysUserPost.class);
			example.createCriteria().andEqualTo("userId", userId);
			sysUserPostMapper.deleteByExample(example);
			// 新增用户与岗位管理
			insertUserPost(sysUser);
		}
		sysUser.setUpdateTime(DateUtil.now());
		this.updateNotNull(sysUser);
	}

	/**
	 * 插入用户关联职位
	 * 
	 * @param sysUser
	 */
	private void insertUserPost(SysUser sysUser) {
		Date now = DateUtil.now();
		for (Long postId : sysUser.getPostIds()) {
			SysUserPost userPost = new SysUserPost();
			userPost.setPostId(postId);
			userPost.setUserId(sysUser.getUserId());
			userPost.setCreateTime(now);
			sysUserPostMapper.insertSelective(userPost);
		}
	}

	@Override
	public boolean isAdmin(Long userId) {
		SysUser sysUser = this.selectByKey(userId);
		return sysUser != null && "00".equals(sysUser.getUserType());
	}

	/**
	 * 校验登录名称是否唯一
	 * 
	 * @param loginName
	 *            用户名
	 * @return
	 */
	@Override
	public String checkLoginNameUnique(String loginName) {
		Example example = new Example(SysUser.class);
		example.createCriteria().andEqualTo("loginName", loginName);
		int count = this.countByExample(example);
		if (count > 0) {
			return "1";
		}
		return "0";
	}

	/**
	 * 校验用户名称是否唯一
	 *
	 * @param user
	 *            用户信息
	 * @return
	 */
	@Override
	public String checkPhoneUnique(String phoneNum) {
		Example example = new Example(SysUser.class);
		example.createCriteria().andEqualTo("phonenumber", phoneNum);
		int count = this.countByExample(example);
		if (count > 0) {
			return "1";
		}
		return "0";
	}

	@Override
	public SysUserVo selectUserById(Long userId) {
		SysUser sysUser = this.selectByKey(userId);
		SysDept sysDept = sysDeptMapper.selectByPrimaryKey(sysUser.getDeptId());
		SysUserVo sysUserVo = new SysUserVo();
		BeanUtils.copyBeanProp(sysUserVo, sysUser);
		sysUserVo.setDept(sysDept);
		return sysUserVo;
	}

	@Override
	public void changeStatus(SysUser sysUser) {
		this.updateUser(sysUser);
	}

	@Override
	public void updateUserRole(Long userId, Long[] roleIds) {
		// 删除用户与角色关联
		Example example = new Example(SysUserRole.class);
		example.createCriteria().andEqualTo("userId", userId);
		sysUserRoleMapper.deleteByExample(example);
		// 新增用户与角色管理
		for (Long roleId : roleIds) {
			SysUserRole userRole = new SysUserRole();
			userRole.setCreateTime(DateUtil.now());
			userRole.setRoleId(roleId);
			userRole.setUserId(userId);
			sysUserRoleMapper.insertSelective(userRole);
		}
	}

	@Override
	public List<SysUserRole> listRealRole(Long userId) {
		// 获取用户与角色关联
		Example example = new Example(SysUserRole.class);
		example.createCriteria().andEqualTo("userId", userId);
		return sysUserRoleMapper.selectByExample(example);
	}

	@Override
	public void resetUserPwd(SysUser sysUser) {
		// 一个Byte占两个字节，此处生成的3字节，字符串长度为6
		String salt = RandomUtil.getRandomChar(6);
		sysUser.setSalt(salt);
		String password = Md5Util.getMd5Passwd(sysUser.getPassword(), sysUser.getSalt());
		sysUser.setPassword(password);
		sysUser.setUpdateTime(DateUtil.now());
		this.updateNotNull(sysUser);
	}

	@Override
	public boolean checkPassword(SysUser sysUser, String password) {
		String passwordMd5 = Md5Util.getMd5Passwd(password, sysUser.getSalt());
		return StringUtils.equals(sysUser.getPassword(), passwordMd5);
	}

	/**
	 * 查询用户所属角色组
	 * 
	 * @param userId
	 *            用户ID
	 * @return 结果
	 */
	@Override
	public String selectUserRoleGroup(Long userId) {
		List<SysRole> list = extSysUserMapper.selectRolesByUserId(userId);
		StringBuffer idsStr = new StringBuffer();
		for (SysRole role : list) {
			idsStr.append(role.getRoleName()).append(",");
		}
		if (StringUtils.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	/**
	 * 查询用户所属岗位组
	 * 
	 * @param userId
	 *            用户ID
	 * @return 结果
	 */
	@Override
	public String selectUserPostGroup(Long userId) {
		List<SysPost> list = extSysUserMapper.selectPostsByUserId(userId);
		StringBuffer idsStr = new StringBuffer();
		for (SysPost post : list) {
			idsStr.append(post.getPostName()).append(",");
		}
		if (StringUtils.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}
	
	public static void main(String[] args) {
//		String password = Md5Util.getMd5Passwd("123456", "2e70cc");
		String password = Md5Util.getMd5Passwd("admin", "2e70cc");
		System.out.println(password);
	}

}
